package tencent

import (
	"context"
	"fmt"
	"github.com/ecodeclub/ekit"
	"github.com/ecodeclub/ekit/slice"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
	"go.uber.org/zap"
)

type SmsService struct {
	appId *string
	signName *string
	client *sms.Client
}

func NewSmsService(client *sms.Client, appId string, signName string) *SmsService{
	return &SmsService{
		// 转换为指针
		appId: ekit.ToPtr(appId),
		signName: ekit.ToPtr(signName),
		client: client,
	}
}

func (s *SmsService) Send(ctx context.Context, biz string, args []string, numbers ...string) error {
	req:=sms.NewSendSmsRequest()
	req.SmsSdkAppId = s.appId
	req.SignName = s.signName
	req.TemplateId = ekit.ToPtr(biz)
	req.PhoneNumberSet = s.toStringPtrSlice(numbers)
	req.TemplateParamSet = s.toStringPtrSlice(args)
	resp, err:=s.client.SendSms(req)
	zap.L().Debug("发送短信，记录请求和响应", zap.Any("req", req), zap.Any("resp", resp))
	if err!=nil{
		return err
	}
	for _, status:=range resp.Response.SendStatusSet {
		if status.Code == nil || *(status.Code) != "Ok" {
			return fmt.Errorf("发送短信失败，错误码：%s，错误信息：%s", &status.Code, &status.Message)
		}
	}
	return nil
}

func (s *SmsService) toStringPtrSlice(src []string) []*string {
	return slice.Map(src, func(idx int, src string) *string{
		return &src
	})
}
